package com.risetechnology.adapter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.customviews.CustomFontTextView;
import com.risetechnology.data.Ingredient;
import com.risetechnology.data.Method;
import com.risetechnology.data.Recipe;
import com.risetechnology.krystalkitchen1.ActivityEditRecipe;
import com.risetechnology.krystalkitchen1.ActivityMasalasRecipeDetails;
import com.risetechnology.krystalkitchen1.ActivityRecipeDetails;
import com.risetechnology.krystalkitchen1.ActivityRecipes;
import com.risetechnology.krystalkitchen1.ActivityViewSchedule;
import com.risetechnology.krystalkitchen1.ChooseEmailDialog;
import com.risetechnology.krystalkitchen1.R;
import com.risetechnology.krystalkitchen1.TabsManager;
import com.risetechnology.master.NavigationActivity;

public class RecipeListAdapter extends ArrayAdapter<Recipe> {

	private Activity context;
	private int layoutId;
	private List<Recipe> data = null;
	private boolean isMasalas = false;
	private Recipe curRecipe;

	public RecipeListAdapter(Activity context, int layoutId, List<Recipe> data) {
		super(context, layoutId, data);
		this.context = context;
		this.layoutId = layoutId;
		this.data = data;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(layoutId, parent, false);

			holder = new ViewHolder();

			holder.imageviewIcon = (ImageView) convertView
					.findViewById(R.id.iv_image);

			holder.textviewName = (CustomFontTextView) convertView
					.findViewById(R.id.tv_name);
			holder.textviewServes = (CustomFontTextView) convertView
					.findViewById(R.id.tv_serves);
			holder.textviewMealType = (CustomFontTextView) convertView
					.findViewById(R.id.tv_main);
			holder.textviewDescription = (CustomFontTextView) convertView
					.findViewById(R.id.tv_main_description);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.textviewName.setText(data.get(position).getName());
		holder.textviewServes.setText(data.get(position).getServes());
		String[] mealTypes = context.getResources().getStringArray(
				R.array.meal_types);
		holder.textviewMealType.setText(mealTypes[data.get(position)
				.getMealType()]);
		holder.textviewDescription.setText(data.get(position)
				.getMainDescription());

		holder.imageviewIcon.setImageDrawable(data.get(position).getImage());

		convertView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				@SuppressWarnings("rawtypes")
				Class clss = ActivityRecipeDetails.class;
				if (isMasalas) {
					clss = ActivityMasalasRecipeDetails.class;
				}
				if (getContext() instanceof ActivityRecipes) {
					ActivityRecipes.recipesSearchBox.setText("");
				}

				Intent intent = new Intent(((NavigationActivity) context)
						.getParent(), clss);
				intent.putExtra(Const.KEY_ID, data.get(position).getId());
				((NavigationActivity) context).goNextHistory("Recipe Details",
						intent);
			}
		});

		
		if(data.get(position).getPackageID()==0){
			convertView.setOnLongClickListener(new OnLongClickListener() {
	
				public boolean onLongClick(View v) {
					curRecipe = data.get(position);
					
					showEditRecipeDialog();
	
					return false;
				}
			});
		}
		return convertView;
	}

	@SuppressWarnings("deprecation")
	private void showEditRecipeDialog() {
		final Dialog dialog = new Dialog(context.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_confirm_recipe);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		dialog.show();
		Button buttonDelete = (Button) dialog.findViewById(R.id.btn_delete);
		buttonDelete.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				Shared.dbAdapter.deleteRecipe(curRecipe.getId());

				ActivityRecipes.getRecipesList();
			}
		});
		Button buttonSaveEdits = (Button) dialog
				.findViewById(R.id.btn_save_edits);
		buttonSaveEdits.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent(((NavigationActivity) context)
						.getParent(), ActivityEditRecipe.class);
				intent.putExtra(Const.KEY_ID, curRecipe.getId());
				((NavigationActivity) context).goNextHistory("Edit Recipe",
						intent);
			}
		});
		Button buttonSend = (Button) dialog
				.findViewById(R.id.btn_send);
		buttonSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				
				openSendMailPicker();
			}
		});
	}

	private void openSendMailPicker(){
		final Dialog dialog = new Dialog(context.getParent());
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_send_email_options);

		Window window = dialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();

		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.FILL_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);

		dialog.getWindow().setAttributes(wlp);

		LinearLayout cameraLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_camera);
		cameraLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(0);
			}
		});

		LinearLayout galleryLayout = (LinearLayout) dialog
				.findViewById(R.id.layout_gallery);
		galleryLayout.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog.dismiss();
				showInputEmailDialog(1);
			}
		});

		dialog.show();
	}
	
	private void showInputEmailDialog(int type) {
		if(type != 0){ // Select from exist
			new ChooseEmailDialog(context.getParent(),
				TabsManager.mails, 
				new ChooseEmailDialog.SelectedListener() {

					@Override
					public void onSelected(ArrayList<String> choosenRecipe) {
						String email = "";
						if(choosenRecipe.size()>0){
							email = choosenRecipe.get(0);
						}
						for (int i = 1; i < choosenRecipe.size(); i++) {
							email += "," + choosenRecipe.get(i);
						}
						
						new GetRecipeData().execute(email);
					}
				}).show();
			
		}else{
			final Dialog dialog = new Dialog(context.getParent());
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.dialog_input_part_name);
	
			Window window = dialog.getWindow();
			WindowManager.LayoutParams wlp = window.getAttributes();
	
			wlp.gravity = Gravity.CENTER;
			wlp.width = WindowManager.LayoutParams.FILL_PARENT;
			wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
			window.setAttributes(wlp);
	
			dialog.getWindow().setAttributes(wlp);
	
			dialog.show();
	
			TextView tv = (TextView) dialog.findViewById(R.id.tv_title);
			tv.setText("Input Email Address");
	
			final EditText edt_email = (EditText) dialog
					.findViewById(R.id.et_part_name);
			edt_email.setHint("Input Email Address");
			edt_email.setInputType(InputType.TYPE_CLASS_TEXT
					| InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
	
			// edt_email.setText("ninhngoc.t4.bkdn@gmail.com");
	
			Button buttonOK = (Button) dialog.findViewById(R.id.btn_ok);
			buttonOK.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					String email = edt_email.getText().toString();
					if (email.trim().length() == 0) {
						Toast.makeText(context.getParent(),
								"Please input email", Toast.LENGTH_SHORT).show();
						return;
					}
					if (!isEmailValid(email)) {
						Toast.makeText(context.getParent(),
								"Please input correct email!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
	
					
	
					new GetRecipeData().execute(email);
	
					dialog.dismiss();
				}
			});
		
		}
	}
	
	private boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}
	
	private class GetRecipeData extends AsyncTask<String, Void, String> {
		private ProgressDialog pd;
		private String email = "";
		private String path = Environment.getExternalStorageDirectory()+"/myapptmp.png";

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(context.getParent());
			pd.setCancelable(false);
			pd.setMessage("Getting recipe data...");
			pd.show();
		}

		@Override
		protected String doInBackground(String... arg0) {
			email = arg0[0];
			
	        try {
		    //convert array of bytes into file
		    FileOutputStream fileOuputStream = new FileOutputStream(path); 
		    fileOuputStream.write(curRecipe.getPictureData());
		    fileOuputStream.close();
	        }catch(Exception e){
	            e.printStackTrace();
	        }
			
			return onSendMail();
		}

		@Override
		protected void onPostExecute(String result) {
			pd.dismiss();
			
			Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
					Uri.fromParts("mailto", email, null));
			emailIntent.putExtra(Intent.EXTRA_SUBJECT, "[KrystalKitchen]Recipe for dish: "+ curRecipe.getName());
			emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(result));
			emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(path)));
			context.startActivity(emailIntent);
		}
	}
	
	private String onSendMail(){
		String text = "Hi,<br/>This is a recipe from KrystalKitchen app.<br/>";
		
		text += "Name: " + curRecipe.getName() + "<br/>";
		text += "Serves: " + curRecipe.getServes() + "<br/>";
		text += "Sumary: " + curRecipe.getMainDescription() + "<br/><br/>";

		//
		// Ingredients
		//
		if(curRecipe.getPart1Name().trim().length()>0 &&
				!curRecipe.getPart1Name().trim().equals("Part 1 Name...")){
			text += curRecipe.getPart1Name() + "<br/>";
		}
		ArrayList<Ingredient> ings1 = Shared.dbAdapter.getIngByRecipe(curRecipe.getId(), 0);
		if(ings1.size()>0){
			for(Ingredient ing : ings1){
				text += ing.getQuantity() +" "+ ing.getUnit() +" "+ing.getName();
			}
			text += "<br/>";
		}
		
		if(curRecipe.getPart2Name().trim().length()>0 &&
				!curRecipe.getPart2Name().trim().equals("Part 2 Name...")){
			text += curRecipe.getPart2Name() + "<br/>";
		}
		ArrayList<Ingredient> ings2 = Shared.dbAdapter.getIngByRecipe(curRecipe.getId(), 1);
		if(ings2.size()>0){
			for(Ingredient ing : ings2){
				text += ing.getQuantity() +" "+ ing.getUnit() +" "+ing.getName();
			}
			text += "<br/>";
		}
		
		if(curRecipe.getPart3Name().trim().length()>0 &&
				!curRecipe.getPart3Name().trim().equals("Part 3 Name...")){
			text += curRecipe.getPart3Name() + "<br/>";
		}
		ArrayList<Ingredient> ings3 = Shared.dbAdapter.getIngByRecipe(curRecipe.getId(), 2);
		if(ings3.size()>0){
			for(Ingredient ing : ings3){
				text += ing.getQuantity() +" "+ ing.getUnit() +" "+ing.getName();
			}
			text += "<br/>";
		}
		
		//
		// Method
		//
		if(curRecipe.getPart1MethodName().trim().length()>0 &&
				!curRecipe.getPart1MethodName().trim().equals("Part 1 Name...")){
			text += curRecipe.getPart1MethodName() + "<br/>";
		}
		
		String[] splittedMethod1 = curRecipe.getPart1Method().replaceAll("\n", "").split("#");
		if (splittedMethod1 != null && splittedMethod1.length > 0) {
			int length = splittedMethod1.length;
			for (int i = 0; i < length; i++) {
				String mt = splittedMethod1[i];
				if (mt.length() > 0){
					text += (i+1) +". "+ mt + "<br/>";
				}
			}
		}
		
		// Method Part 2
		if(curRecipe.getPart2MethodName().trim().length()>0 &&
				!curRecipe.getPart2MethodName().trim().equals("Part 2 Name...")){
			text += curRecipe.getPart2MethodName() + "<br/>";
		}
		
		String[] splittedMethod2 = curRecipe.getPart2Method().replaceAll("\n", "").split("#");
		if (splittedMethod2 != null && splittedMethod2.length > 0) {
			int length = splittedMethod2.length;
			for (int i = 0; i < length; i++) {
				String mt = splittedMethod2[i];
				if (mt.length() > 0){
					text += (i+1) +". "+ mt + "<br/>";
				}
			}
		}
		
		// Method Part 3
		if(curRecipe.getPart3MethodName().trim().length()>0 &&
				!curRecipe.getPart3MethodName().trim().equals("Part 3 Name...")){
			text += curRecipe.getPart3MethodName() + "<br/>";
		}
		
		String[] splittedMethod3 = curRecipe.getPart3Method().replaceAll("\n", "").split("#");
		if (splittedMethod3 != null && splittedMethod3.length > 0) {
			int length = splittedMethod3.length;
			for (int i = 0; i < length; i++) {
				String mt = splittedMethod3[i];
				if (mt.length() > 0){
					text += (i+1) +". "+ mt + "<br/>";
				}
			}
		}
		
		text += "<br/>Have a delecious meal!";
		
		return text;
	}
	
	public boolean isMasalas() {
		return isMasalas;
	}

	public void setMasalas(boolean isMasalas) {
		this.isMasalas = isMasalas;
	}

	static class ViewHolder {
		ImageView imageviewIcon;
		TextView textviewName;
		TextView textviewServes;
		TextView textviewMealType;
		TextView textviewDescription;
	}

}
